package org.dragonnova.meetingclient.core.net.netty;

import org.dragonnova.meetingclient.core.message.GroupMessage;
import org.dragonnova.meetingclient.utils.LogUtil;

import java.util.List;

import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.ByteToMessageDecoder;

/**
 * Created by hucn on 2016/5/19.
 * Description: 用于Netty的ChannelInitializer中，解析发送过来的TCP的包的内容
 */
public class MsgDecoder extends ByteToMessageDecoder {

    private static final String TAG = MsgDecoder.class.getName();
    private static final int iNeedContentLen = (Integer.SIZE / 8) * 2; //TCP包的最小大小

    @Override
    protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) {
        LogUtil.i(TAG, "start decoding...");
        if (in.readableBytes() < iNeedContentLen) return;
        if (in.nioBufferCount() > 0) {
            int len = in.readableBytes();
            byte[] bytes = new byte[len];
            in.readBytes(bytes);
            out.add(new GroupMessage().decode(bytes));
        }
    }
}
